package com.cicadamob.contact.api.group.asynctask;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.ContentValues;
import android.content.Context;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;

import com.cicadamob.contact.api.Utils.ContactConfig;
import com.cicadamob.contact.api.Utils.StringUtil;
import com.cicadamob.contact.api.Utils.Logger.AppLogger;
import com.cicadamob.contact.api.Utils.NetWork.HttpRequestCallBack;
import com.cicadamob.contact.api.Utils.NetWork.HttpUtil;
import com.cicadamob.contact.api.Utils.NetWork.NetWorkUtil;
import com.cicadamob.contact.api.Utils.NetWork.HttpUtil.RequestMethod;
import com.cicadamob.contact.api.group.bean.Group;
import com.cicadamob.contact.api.group.bean.ResultModel;
import com.cicadamob.contact.api.group.dao.Group_Db_Dao;
import com.cicadamob.contact.api.group.http.Http_Group_Util;
import com.cicadamob.contact.api.group.http.JsonParseUtil;
import com.cicadamob.contact.api.service.ServerUrl;
import com.cicadamob.contact.api.service.AppDbHelper.TS_DATA_VERSION;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;

public class LoadGroup implements Runnable {
	
	private Handler mHandler;
	private int what;
	private Context mContext;
	private Group_Db_Dao dbHelper;
	private boolean isFromNet=false;
	public LoadGroup(Handler mHandler,Context mContext,int what,boolean isFromNet){
		this.mHandler=mHandler;
		this.what=what;
		this.mContext=mContext;
		this.isFromNet=isFromNet;
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		dbHelper= Group_Db_Dao.getInstance(mContext);
		
	   
		final List<String> olderids = dbHelper.queryOlderGroupIds();
		
		if (!NetWorkUtil.isConnected(mContext)) {
			 ResultModel resultmodel = new ResultModel();
			 resultmodel.setRetcode(0);
			if (olderids.size() == 0) {
				dbHelper.updateAllGroupState();
			}
			List<Group>	sContacts = new ArrayList<Group>();
			sContacts = dbHelper.queryAllGroup();
			resultmodel.setResultData(sContacts);
			 mHandler.obtainMessage(what, resultmodel).sendToTarget();
			return ;// 网络异常
		}

		if (isFromNet) {
			mHandler.post(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					String xmlData=Http_Group_Util.get_GroupAndMemberXML(dbHelper.getGroupAndMemberTimeStamp(TS_DATA_VERSION.GROUP_LIST_AND_MEMBER));
					Map<String, String> requestMap=new HashMap<String, String>();
					requestMap.put(HttpUtil.XML, xmlData);
					Log.e("网络请求 ServerUrl.GET_GROUP_AND_MEMBER  \r\n", xmlData);
					AppLogger.writeLogToFile(mContext, ContactConfig.DIRECTORY+"/httpGroupLog", "msg_group", "发送报文  url =" + ServerUrl.GET_GROUP_AND_MEMBER
				    		+"\r\n xml ="+xmlData, true);			
					HttpUtil.HttpRequest(mContext, RequestMethod.POST, ServerUrl.GET_GROUP_AND_MEMBER, true,requestMap, new HttpRequestCallBack<String>(){

						@Override
						public void onSuccess(ResponseInfo<String> responseInfo) {
							// TODO Auto-generated method stub
							AppLogger.writeLogToFile(mContext, ContactConfig.DIRECTORY+"/httpGroupLog", "msg_group", "响应报文  url =" + ServerUrl.GET_GROUP_AND_MEMBER
						    		+"\r\n xml ="+responseInfo.result, true);	
							odResult(responseInfo.result, olderids);
						}

						@Override
						public void onFailure(HttpException error, String msg) {
							// TODO Auto-generated method stub
							Log.e("网络请求失败", msg);
							 ResultModel resultmodel = new ResultModel();
							 resultmodel.setRetcode(-8);
							 List<Group> sContacts = dbHelper.queryAllGroup();
								resultmodel.setResultData(sContacts);
							 Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
							 mHandler.obtainMessage(what, resultmodel).sendToTarget();
						}
						
					});
				}
			});
			
		}else{
			 ResultModel resultmodel = new ResultModel();
			 resultmodel.setRetcode(0);
			 List<Group> sContacts = dbHelper.queryAllGroup();
				resultmodel.setResultData(sContacts);
//			 Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
			 mHandler.obtainMessage(what, resultmodel).sendToTarget();
		}
			
	}
	
	private void odResult(String result,List<String> olderids){
		 ResultModel resultmodel = new ResultModel();
		 List<Group>	sContacts = new ArrayList<Group>();
			
			resultmodel = Http_Group_Util.parseResult(result);
			if (resultmodel.getRetcode() == 0) {
				String groupSqlStr = resultmodel.getGrouplist();
				String memberSqlStr = resultmodel.getGroupmembers();
				List<String> sqlList = new ArrayList<String>();
				if (!StringUtil.isEmpty(groupSqlStr)) {
					sqlList.addAll(JsonParseUtil
							.jsonTOStringGroupList(groupSqlStr));
					
				}
				
				if (!StringUtil.isEmpty(memberSqlStr)) {
					sqlList.addAll(JsonParseUtil
							.jsonTOStringMemberList(memberSqlStr));
						
				}
				if (sqlList.size() > 0) {
					dbHelper.executesql(sqlList);
				}
				
				if (!StringUtil.isEmpty(groupSqlStr)) {
					
					try {
						JSONObject obj = new JSONObject(groupSqlStr);
						JSONArray ids=obj.optJSONArray("groupInfo");
						Group_Db_Dao groupDao=Group_Db_Dao.getInstance(mContext);
						ContentValues values=new ContentValues();
						for (int i = 0; i < ids.length(); i++) {
							JSONObject item=ids.getJSONObject(i);
							String groupId=item.getString("groupId");
							String assetId=item.getString("assetId");	
							
							values.put("assetId", assetId);
							groupDao.updateGroupById(values, groupId);
						}
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				
				String lastupdatetime = resultmodel.getLastupdatetime();
				if (olderids.size() == 0) {
					dbHelper.delGroupVersion();
				}

				dbHelper.updateVersion(TS_DATA_VERSION.GROUP_LIST_ID,
						lastupdatetime);
				dbHelper.updateVersion(
						TS_DATA_VERSION.GROUP_LIST_AND_MEMBER,
						lastupdatetime);
				List<Group> groups = dbHelper.queryAllGroup();
				for (Group group : groups) {
//					if (olderids.size() == 0) {
//						dbHelper.updateVersion(group.getGroup_id(),
//								lastupdatetime);
//					}

					Log.i("群组id", "groupId=="+group.getGroup_id());
					dbHelper.updateVersion(group.getGroup_id(),
							lastupdatetime);
					
					if (olderids.size() > 0
							&& !olderids.contains(group.getGroup_id())) {
						dbHelper.updateGroupStateById(
								group.getGroup_id(), 1);
					}
				}
				if (olderids.size() == 0) {
					dbHelper.updateAllGroupState();
				}
//				if (olderids.size() > 0) {
//					for (String groupid : olderids) {
//						dbHelper.updateVersionNoCreate(groupid,
//								lastupdatetime);
//					}
//				}

			}


		sContacts.clear();
		sContacts = dbHelper.queryAllGroup();
		resultmodel.setResultData(sContacts);
		if(mHandler!=null)
		 mHandler.obtainMessage(what, resultmodel).sendToTarget();
	}

}
